
package com.xiaoma.myaudience.biz.activity;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.ProgressBar;

import com.xiaoma.myaudience.R;
import com.xiaoma.myaudience.biz.app.AudienceApplication;
import com.xiaoma.myaudience.biz.model.UserAccount;
import com.xiaoma.myaudience.biz.task.CategoryOptionInfoTask;
import com.xiaoma.myaudience.biz.task.DataAsyncTask;
import com.xiaoma.myaudience.biz.task.FirstPageInfoTask;
import com.xiaoma.myaudience.biz.task.LoginTask;
import com.xiaoma.myaudience.biz.task.LoginTask.LoginStatus;
import com.xiaoma.myaudience.util.Logger;
import com.xiaoma.myaudience.util.NetUtils;
import com.xiaoma.myaudience.util.activity.BaseActivity;

/**
 * 欢迎,预加载界面. <br/>
 * 
 */
public class WelcomeActivity extends BaseActivity {
    private static final String TAG = "WelcomeActivity";

    private static final int DIALOG_EXIT = 0;

    private static final int DIALOG_NET_UNAVAILABLE = DIALOG_EXIT + 1;

    private static final int DIALOG_NET_NOT_WIFI = DIALOG_NET_UNAVAILABLE + 1;

    private ProgressBar mProgressBar;
    
    private LoginTask mLoginTask;
    
    private FirstPageInfoTask mFirstPageInfoTask;

    private Bundle mData;

	private CategoryOptionInfoTask mOptionInfoTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        makeFullScreen(true);
        setContentView(R.layout.welcome);

        mProgressBar = (ProgressBar) findViewById(R.id.welcome_pb);
        
//        MobileAgent.getErrorOnCreate(this);
//        MobileAgent.sessionStart(this);
        
        setProgressBar(10);
        Logger.d(TAG, "  check network");
        if (!NetUtils.isAvailable(this)) {
            // 网络不可用
            showDialog(DIALOG_NET_UNAVAILABLE);
        } else if (!NetUtils.isWIFI(this)) {
        	startLoadingTask();
            // 当前网络不是wifi
//            showDialog(DIALOG_NET_NOT_WIFI);
        } else {
            startLoadingTask();
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_EXIT: {
                AlertDialog.Builder builder = new Builder(this);
                builder.setPositiveButton(R.string.yes, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        WelcomeActivity.this.finish();
                    }
                }).setNegativeButton(R.string.no, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                    }
                }).setMessage(R.string.msg_exit);
                return builder.create();
            }
            case DIALOG_NET_UNAVAILABLE: {
                AlertDialog.Builder builder = new Builder(this);
                builder.setPositiveButton(R.string.confirm, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        WelcomeActivity.this.finish();
                    }
                }).setMessage(R.string.msg_net_unavailable).setCancelable(false);
                return builder.create();
            }
            case DIALOG_NET_NOT_WIFI: {
                AlertDialog.Builder builder = new Builder(this);
                builder.setPositiveButton(R.string.yes, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        startLoadingTask();
                    }
                }).setNegativeButton(R.string.no, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        WelcomeActivity.this.finish();
                    }
                }).setMessage(R.string.msg_net_not_wifi).setCancelable(false);
                return builder.create();
            }
            default:
                break;
        }
        return super.onCreateDialog(id);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            showDialog(DIALOG_EXIT);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelLoadingTask();
    }

    private void startLoadingTask() {
        cancelLoadingTask();
        mFirstPageInfoTask = new FirstPageInfoTask(this, this);
        mFirstPageInfoTask.execute();
        
		mOptionInfoTask = new CategoryOptionInfoTask(this, DataAsyncTask.TASK_CATEGORY_OPTION, this);
//		mOptionInfoTask.execute(CategoryActivity.FILM_SPEC, CategoryActivity.TV_SPEC, CategoryActivity.DOC_SPEC);
		
        AudienceApplication app = (AudienceApplication)getApplication();
        UserAccount userAccount = new UserAccount();
        userAccount.mAccount = app.getUserAccount();
        userAccount.mPassword = app.getUserPassword();
        mLoginTask = new LoginTask(this, DataAsyncTask.TASK_LOGIN, this);
        mLoginTask.execute(userAccount);
        
        setProgressBar(20);
        Logger.d(TAG, " start loading data");
    }

    private void cancelLoadingTask() {
        if (mFirstPageInfoTask != null) {
            mFirstPageInfoTask.cancel();
        }
        mFirstPageInfoTask = null;
        
        if (mLoginTask != null) {
            mLoginTask.cancel(true, true);
        }
        mLoginTask = null;
        
		if (mOptionInfoTask != null) {
			mOptionInfoTask.cancel(true, true);
		}
		mOptionInfoTask = null;
    }

    /**
     * 加载数据完成,启动首页VideoMainActivity.
     * 
     * @param b
     */
    private void startMainActivity() {
//        Intent intent = new Intent(this, VideoMainActivity.class);
//        intent.putExtra(VideoMainActivity.HOME_SPEC, mData);
//        startActivity(intent);
        finish();
    }

    @Override
    public void onPostExecute(int what, Object o) {
        super.onPostExecute(what, o);
        if (false && o == null) {
            // TODO 有加载错误...
        } else {
            switch (what) {
                case DataAsyncTask.TASK_CATEGORY_OPTION:
            	    setProgressBar(10);
            	    break;
                case DataAsyncTask.TASK_FIRST_PAGE_INFO:
                    mData = (Bundle)o;
                    setProgressBar(20);
                    break;
                case DataAsyncTask.TASK_SUBCRIBE:
                    Logger.d(TAG, " load subscribe over ");
                    setProgressBar(20);
                    break;
                case DataAsyncTask.TASK_PALY_RECORD:
                    Logger.d(TAG, " load playrecord over ");
                    setProgressBar(20);
                    break;
                case DataAsyncTask.TASK_LOGIN: {
                    LoginStatus logStatus = (LoginStatus) o;
                    if (logStatus != null && logStatus.mCodeStatus == 1) {
                        AudienceApplication app = (AudienceApplication) getApplication();
                        if (app.isLogin()) {
                            String userid = app.getUserAccount();
                            Logger.d(TAG, " is Login userid = " + userid);
                        } else {
                            Logger.d(TAG, " not login");
                            setProgressBar(40);
                            return;
                        }
                    } else {
                        Logger.d(TAG, " not login");
                        setProgressBar(40);
                        return;
                    }
                    
                }
                default:
                    break;
            }
        }
    }

    /**
     * 更新进度条
     * 
     * @param progress
     */
    private void setProgressBar(int progress) {
        mProgressBar.setProgress(mProgressBar.getProgress() + progress);
        if (mProgressBar.getProgress() >= 100) {
            Logger.d(TAG, "  loading over!!!");
            startMainActivity();
        }
    }

}
